package org.mspring.mlog.web.module.web.ucenter.admin;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.security.UserService;
import org.mspring.mlog.utils.AvatarUtils;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.utils.ImageUtils;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户相关
 * 
 * @author Gao Youbo
 * @since 2013年7月10日
 */
@Widget
@RequestMapping("/u/{username}/admin/user")
public class UCenterAdmin_UserWidget extends Abstract_UCenterAdminWidget {
    @Autowired
    private UserService userService;

    /**
     * 用户信息
     * 
     * @param spaceUser
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/info")
    public String info(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        user = userService.get(spaceUser.getId());
        model.addAttribute("user", user);
        return "skin:/ucenter/admin/user/info";
    }

    /**
     * 执行更新用户信息
     * 
     * @param spaceUser
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/info/do")
    public String info_do(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        // 权限验证
        User currentUser = SecurityUtils.getCurrentUser(request);
        if (currentUser == null || !currentUser.getName().equals(user.getName())) {
            return error(model, "系统提示", "无权操作");
        }

        userService.update(user);
        return String.format("forward:/u/%s/admin/user/info", user.getName());
    }

    /**
     * 密码修改
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/pwd")
    public String pwd(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "skin:/ucenter/admin/user/pwd";
    }

    /**
     * 执行密码修改
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/pwd/do")
    public String pwd_do(@PathVariable String username, HttpServletRequest request, HttpServletResponse response, Model model) {
        String oldPwd = RequestUtils.getRequestParameterAsString(request, "oldPwd");
        String newPwd = RequestUtils.getRequestParameterAsString(request, "newPwd");
        String rePwd = RequestUtils.getRequestParameterAsString(request, "rePwd");

        // 权限验证
        User currentUser = SecurityUtils.getCurrentUser(request);
        if (!username.equals(currentUser.getName())) {
            return error(model, "系统提示", "无权操作");
        }

        if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd) || StringUtils.isBlank(rePwd)) {
            return error(model, "系统提示", "请检查表单是否填写完整", "返回重新输入");
        }

        if (!newPwd.equals(rePwd)) {
            return error(model, "系统提示", "两次输入密码不匹配", "返回重新输入");
        }

        if (!StringUtils.getMD5(oldPwd).equals(spaceUser.getPassword())) {
            return error(model, "系统提示", "原始密码不匹配", "返回重新输入");
        }
        spaceUser.setPassword(StringUtils.getMD5(newPwd));
        userService.update(spaceUser);
        return success(model, "系统提示", "密码修改成功", "");
    }

    /**
     * 进入图像修改页
     * 
     * @param spaceUser
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/avatar")
    public String avatar(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "skin:/ucenter/admin/user/avatar";
    }

    /**
     * 图像上传
     * 
     * @param spaceUser
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/avatar/upload")
    @ResponseBody
    public ResponseEntity avatar_upload(@RequestParam("avatar") MultipartFile avatar, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        // 限定上传图片的格式
        boolean isImage = ImageUtils.isImage(FilenameUtils.getExtension(avatar.getOriginalFilename()));
        if (!isImage) {
            rsp.setSuccess(false);
            rsp.setMessage("上传文件格式不正确");
            return rsp;
        }
        // 限定上传图片大小
        long size = avatar.getSize() / 1024;
        if (size > 512) {
            rsp.setSuccess(false);
            rsp.setMessage("上传图片大不能超过512K");
            return rsp;
        }

        String url = AvatarUtils.uploadAvatar(avatar, spaceUser.getId());
        if (url == null) {
            rsp.setSuccess(false);
            rsp.setMessage("头像上传失败");
        } else {
            rsp.setSuccess(true);
            rsp.put("url", UploadUtils.UPLOAD_FOLDER + url);
        }
        return rsp;
    }

    /**
     * 图像剪裁
     * 
     * @param spaceUser
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/avatar/cut")
    public String avatar_cut(HttpServletRequest request, HttpServletResponse response, Model model) {
        Integer x1 = RequestUtils.getRequestParameterAsInteger(request, "x1");
        Integer y1 = RequestUtils.getRequestParameterAsInteger(request, "y1");
        Integer x2 = RequestUtils.getRequestParameterAsInteger(request, "x2");
        Integer y2 = RequestUtils.getRequestParameterAsInteger(request, "y2");
        String filePath = request.getParameter("file");

        if (x1 == null || x2 == null || y1 == null || y2 == null) {
            return error(model, "系统提示", "请先选择要裁剪的区域");
        }
        if (StringUtils.isBlank(filePath)) {
            return error(model, "系统提示", "头像文件不存在");
        }

        File file = UploadUtils.getAbsoluteUploadFile(filePath);

        if (!file.exists()) {
            return error(model, "系统提示", "头像文件不存在");
        }

        try {
            // 剪裁图片
            BufferedImage image = AvatarUtils.cropAvatar(file, spaceUser.getId(), x1, y1, x2, y2);
            // 保存图像
            String large = AvatarUtils.buildLargeAvatar(image, spaceUser.getId());
            String small = AvatarUtils.buildSmallAvatar(image, spaceUser.getId());

            // 删除头像所使用的零时文件
            ServiceFactory.getFileService().deleteFile(filePath);

            // 更新用户信息
            spaceUser.setLargeAvatar(large);
            spaceUser.setSmallAvatar(small);
            userService.update(spaceUser);
            return success(model, "系统提示", "头像修改成功");
        } catch (IOException e) {
            // TODO: handle exception
            return error(model, "系统提示", "头像修改失败");
        }
    }
}
